import sys, os, time, getopt, subprocess

abspath = lambda d: os.path.abspath(os.path.join(d))

HOME = abspath(os.path.dirname(__file__))

# === 替代 execfile ===
splashrun = {}
splashrun_path = os.path.join(HOME, 'splash2', 'splashrun')
with open(splashrun_path, 'r') as f:
    exec(f.read(), splashrun)

def allbenchmarks():
    result = subprocess.Popen(
        [f'{HOME}/splash2/splashrun', '-l'],
        stdout=subprocess.PIPE
    ).communicate()[0]

    return result.decode().split()

def allinputs():
    return ('test', 'tiny', 'small', 'large')

class Program:

    def __init__(self, program, nthreads, inputsize, benchmark_options=[]):
        if program not in allbenchmarks():
            raise ValueError(f"Invalid benchmark {program}")
        if inputsize not in allinputs():
            raise ValueError(f"Invalid input size {inputsize}")
        self.program = program
        self.nthreads = int(nthreads)
        self.inputsize = inputsize
        splashrun['benchmarks'][self.program].validate(self.inputsize, self.nthreads)

    def run(self, graphitecmd, postcmd=''):
        if postcmd != '':
            sys.stderr.write('Splash2 run error: postcmd currently not supported\n')
            return 1
        proc = subprocess.Popen([
            f'{HOME}/splash2/splashrun',
            '-p', self.program,
            '-i', self.inputsize,
            '-n', str(self.nthreads),
            '-s', graphitecmd
        ])
        proc.communicate()
        return proc.returncode

    def rungraphiteoptions(self):
        return ''
